package com.heima.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.PageResult;
import com.heima.pojo.Node;
import com.heima.mapper.NodeMapper;
import com.heima.pojo.vo.NodeVo;
import com.heima.pojo.vo.RegionVo;
import com.heima.pojo.vo.VendingMachineVo;
import com.heima.service.INodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 点位表 服务实现类
 *
 * @author xjy
 * @since 2024-06-05
 */
@Service
public class NodeServiceImpl extends ServiceImpl<NodeMapper, Node> implements INodeService {
    @Autowired
    private NodeMapper nodeMapper;
    @Autowired
    private IRegionService regionService;

    /**
     * 分页查询点位
     *
     * @param regionId 区域Id
     * @return
     */
    @Override
    public PageResult<NodeVo> PageSearch(PageResult<NodeVo> pageResult, Long regionId) {
        Page<NodeVo> page = new Page<>(pageResult.getPageIndex(), pageResult.getPageSize());
        nodeMapper.pageSearch(page, regionId);
        List<NodeVo> nodeVos = page.getRecords();
        List<String> regionIds = nodeVos.stream().map(NodeVo::getRegionId).collect(Collectors.toList());
        List<RegionVo> regionVos = regionService.batchSelectByIds(regionIds);
        List<RegionVo> collect = regionVos.stream().distinct().collect(Collectors.toList());
        nodeVos.forEach(nodeVo -> {
            collect.forEach(regionVo -> {
                if (nodeVo.getRegionId().equals(regionVo.getId() + "")) {
                    nodeVo.setRegion(regionVo);
                }
            });
        });
        return pageResult.of(page, NodeVo.class);
    }

    /**
     * 根据Id点位详情
     *
     * @param nodeId 点位Id
     * @return
     */
    @Override
    public NodeVo getDetailById(Long nodeId) {
        NodeVo detailById = nodeMapper.getDetailById(nodeId);
        RegionVo byId = regionService.findById(Long.valueOf(detailById.getRegionId()));
        detailById.setRegion(byId);
        return detailById;
    }

    /**
     * 合作商点位汇总统计
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> nodeCollect() {
        return nodeMapper.nodeCollect();
    }

}
